package com.sq.util.check;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sq.util.IOUtil;
import com.sq.util.StringUtil;

public class CdnFileChecker {
    private static final Logger log = LoggerFactory.getLogger(CdnFileChecker.class);

    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000)
            .setConnectionRequestTimeout(6000).build();

    private static boolean compareStream(InputStream is1, InputStream is2) throws Exception {
        byte[] arr1 = new byte[128];
        byte[] arr2 = new byte[128];
        while (is1.read(arr1) > -1) {
            is2.read(arr2);
            if (!Arrays.equals(arr1, arr2)) {
                return false;
            }
        }
        return true;
    }

    public static boolean check(String url, String filePathName) {
        if (StringUtil.isBlank(url) || StringUtil.isBlank(filePathName)) {
            return false;
        }
        return compareContent(url, filePathName);
    }

    /**
     * 比较网络和本地文件内容
     */
    private static boolean compareContent(String url, String filePathName) {
        InputStream is1 = null, is2 = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpGet httpGet = new HttpGet(url);
        try {
            httpClient = HttpClients.createDefault();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                is1 = entity.getContent();

                File file = new File(filePathName);
                if (!file.exists()) {
                    return false;
                }
                is2 = new FileInputStream(file);
                return compareStream(is1, is2);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtil.closeQuietly(is1);
            IOUtil.closeQuietly(is2);
            IOUtil.closeQuietly(response);
            IOUtil.closeQuietly(httpClient);
        }
        return false;
    }

}